package com.sean.community.service;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.sean.community.dao.DiscussPostMapper;
import com.sean.community.entity.DiscussPost;
import com.sean.community.util.SensitiveFilter;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class DiscussPostService {

    private Logger logger = LoggerFactory.getLogger(DiscussPostService.class);

    private DiscussPostMapper discussPostMapper;

    private SensitiveFilter sensitiveFilter;

    // Caffeine 核心接口： Cache， LoadingCache(同步缓存), AsyncLoadingCache(异步)

    // 帖子列表的缓存 k-v
    private LoadingCache<String, List<DiscussPost>> discussPostListCache;
    // 帖子总数缓存
    private LoadingCache<Integer, Integer> discussPostRowCache;

    @Value("${caffeine.discusspost.max-size}")
    private int caffeine_discusspost_maxSize;

    @Value("${caffeine.discusspost.expire-seconds}")
    private int caffeine_discusspost_expire_seconds;

    @Autowired
    public void setDiscussPostMapper(DiscussPostMapper discussPostMapper) {
        this.discussPostMapper = discussPostMapper;
    }

    @Autowired
    public void setSensitiveFilter(SensitiveFilter sensitiveFilter) {
        this.sensitiveFilter = sensitiveFilter;
    }

    @PostConstruct
    public void init(){
        // 初始化帖子缓存列表
        discussPostListCache = Caffeine.newBuilder()
                .maximumSize(caffeine_discusspost_maxSize)
                .expireAfterAccess(caffeine_discusspost_expire_seconds, TimeUnit.SECONDS)
                .build(new CacheLoader<String, List<DiscussPost>>() {
                    @Nullable
                    @Override
                    // 缓存数据来源
                    public List<DiscussPost> load(@NonNull String key) throws Exception {
                        if(key.length() <= 0){
                            throw new RuntimeException("参数错误!");
                        }
                        String[] params = key.split(":");
                        if (params == null || params.length != 2){
                            throw new RuntimeException("参数错误!");
                        }
                        int offset = Integer.parseInt(params[0]);
                        int limit = Integer.parseInt(params[1]);
                        // 可以加二级缓存 Redis
                        logger.debug("load post list from DB.");
                        return discussPostMapper.selectDiscussPosts(0, offset, limit, 1);
                    }
                });
        // 初始化
        discussPostRowCache = Caffeine.newBuilder()
                .maximumSize(caffeine_discusspost_maxSize)
                .expireAfterAccess(caffeine_discusspost_expire_seconds, TimeUnit.SECONDS)
                .build(new CacheLoader<Integer, Integer>() {
                    @Nullable
                    @Override
                    public Integer load(@NonNull Integer key) throws Exception {
                        logger.debug("load post list from DB.");
                        return discussPostMapper.selectDiscussPostRows(key);
                    }
                });
    }

    public List<DiscussPost> findDiscussPosts(int userId, int offset, int limit, int orderMode){
        // 如果按热点排行，走缓存， 10w 数据 100 线程并发，1分钟吞吐量 194.4/sec
        if(userId == 0 && orderMode == 1){
            return discussPostListCache.get(offset + ":" + limit);
        }
        // 不走缓存，10w 数据 100 线程并发，1分钟吞吐量 44.6/sec
        logger.debug("load post list from DB.");
        return discussPostMapper.selectDiscussPosts(userId, offset, limit, orderMode);
        // 一对多外键, 帖子表中用户 id 是外键, 需要同时查出用户
        // 1. 连接查询
        // 2. 查出每一个 Post 再查取 user 手动组合
        // 采用 2 看似麻烦,但使用 Redis 缓存数据时比较方便.
    }

    @SuppressWarnings("all")
    public int findDiscussPostRows(int userId){
        // 可走本地缓存，总行数影响总页数，总页数少了一页关系不大
        if(userId == 0){
            return discussPostRowCache.get(userId);
        }
        return discussPostMapper.selectDiscussPostRows(userId);
    }

    public int addDiscussPost(DiscussPost discussPost){
        if(discussPost == null){
            throw new IllegalArgumentException("参数不能为空！");
        }
        // XSS 过滤，通过转义
        discussPost.setTitle(HtmlUtils.htmlEscape(discussPost.getTitle()));
        discussPost.setContent(HtmlUtils.htmlEscape(discussPost.getContent()));
        // 敏感词过滤
        discussPost.setTitle(sensitiveFilter.filter(discussPost.getTitle()));
        discussPost.setContent(sensitiveFilter.filter(discussPost.getContent()));
        return discussPostMapper.insertDiscussPost(discussPost);
    }

    public DiscussPost findDiscussPostById(int id){
        return discussPostMapper.selectDiscussPostById(id);
    }

    /**
     * 根据 id 更新帖子评论数量
     * @param id 帖子 id
     * @param commentCount 评论数量
     * @return 影响行数
     */
    public int updateCommentCount(int id, int commentCount){
        return discussPostMapper.updateCommentCount(id, commentCount);
    }

    public int updateTypeById(int id, int type){
        return discussPostMapper.updateTypeById(id, type);
    }

    public int updateStatusById(int id, int status){
        return discussPostMapper.updateStatusById(id, status);
    }

    public int updateScoreById(int id, double score){
        return discussPostMapper.updateScoreById(id, score);
    }
}
